import 'isomorphic-fetch'
import jwtDecode from 'jwt-decode'
import {
	TOKEN,
} from '../constants'

/*
*  对于非 2xx 的 response code, 当做错误处理
* */
function checkResponseStatus(response) {
	if (!response.ok) {
		let error = new Error(response.status, response.statusText)
		error.body = response.json()
		throw error
	}
	return response
}

/*
* 如果 response 有 errorCode 字段, 说明出错
* */
function analyzeResponse(response) {
	if (response.errorCode) {
		return ({
			occurRestException: true,
			errorCode: response.errorCode,
			errorMessage: response.errorMessage,
		})
	}
}

/*
*  通过 fetch 发起请求, 返回 Promise
* */
export function restCall(url, requestConfig, successCallback, failedCallback, skipToJson = false) {
	return dispatch => {
		fetch(url, requestConfig)
			.then(checkResponseStatus)
			.then(response => (skipToJson ? response.text() : response.json()))
			.then(json => dispatch(successCallback(json)))
			.catch(error => {
				/*
				 Todo: 统一错误处理:
				 token 过期处理. 触发 tokenExpiredAction, 让 baseFrame 页面处理, 跳转 login 页面
				* */
				if(error.body) {
					error.body.then(errMsg => {
						console.log('Exception:', errMsg)
						dispatch(failedCallback(errMsg))
					})
				} else {
					dispatch(failedCallback({errorCode: 500, errorMessage: "Internal error."}))
				}
			})
	}
}

/*
* 对 sessionStorage 进行 get/set/remove
* */
export function setItem(key, value) {
	sessionStorage.setItem(key, value)
}
export function getItem(key) {
	return sessionStorage.getItem(key)
}
export function removeItem(key) {
	sessionStorage.removeItem(key)
}

export function getUserProfile() {
	return sessionStorage.getItem(TOKEN) ? jwtDecode(sessionStorage.getItem(TOKEN)) : null
}

export function getUserId() {
	return getUserProfile() ? getUserProfile().sub : ""
}